package org.maxgroundstation.groundstation.comm.service;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Handles all UDP service communication.
 * @author Scott Davis
 * 
 * Copyright (C) 2010  Scott Davis
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class ServiceCommunicationUDP {

	// Default UDP port.
	private static final int DEFAULT_PORT = 10002;
	
	// Data members
	private ServiceCommunication comm;
	private ServiceSenderUDP sender;
	private ServiceReceiverUDP receiver;
    private DatagramSocket socket;
    private int port;
    
    /**
     * Constructor
     * @param comm the service communication.
     */
	ServiceCommunicationUDP(ServiceCommunication comm) {
		this.comm = comm;
		port = DEFAULT_PORT;
		sender = new ServiceSenderUDP(this);
		receiver = new ServiceReceiverUDP(this);
		
		try {
            socket = new DatagramSocket();
        }
        catch (IOException e) {
            System.err.println("Error opening datagram socket: " + e.getMessage());
        }
	}
	
    /**
     * Gets the service communication.
     * @return service communication.
     */
    ServiceCommunication getServiceCommunication() {
    	return comm;
    }
    
    /**
     * Gets the current port number.
     * @return port number.
     */
    public int getPort() {
        return port;
    }
    
    /**
     * Sets the port number.
     * @param port the new port number.
     */
    public void setPort(int port) {
        this.port = port;
    }
    
    /**
     * Connect to the robot via UDP.
     * @throws IOException if error connecting to robot.
     */
    public void connect() throws IOException {
        if (!isConnected()) {
            if (socket.isClosed()) socket = new DatagramSocket();
            InetAddress address = InetAddress.getByName(comm.getIPAddress());
            socket.connect(address, port);
            
            receiver.start();
        }
    }
    
    /**
     * Disconnect UDP connection from the robot.
     * @throws IOException if error disconnecting from robot.
     */
    public void disconnect() throws IOException {
        if (isConnected()) {
        	System.out.println("Disconnecting UDP service socket");
            socket.close();
        }
    }
    
    /**
     * Checks if connected to robot.
     * @return true if connected
     */
    public boolean isConnected() {
        return (socket != null) && socket.isConnected() && !socket.isClosed();
    }
    
    /**
     * Gets the datagram socket.
     * @return the datagram socket.
     */
    public DatagramSocket getSocket() {
    	return socket;
    }
    
    /**
     * Sends a service post with data to the robot.
     * @param serviceID the service ID string.
     * @param data the data bytes.
     * @throws Exception if error sending service post.
     */
    public void sendServicePost(String serviceID, byte[] data) throws Exception {
    	if (data == null) throw new IllegalArgumentException("data cannot be null");
    	sender.sendServicePost(serviceID, data);
    }
}